package com.example.springboot3demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class ThreadPoolConfig {

    // 自定义TaskDecorator实现
    public static class CustomTaskDecorator implements TaskDecorator {
        @Override
        public Runnable decorate(Runnable runnable) {
            // 这里可以自定义逻辑，比如传递ThreadLocal、MDC等
            // 示例：简单打印线程名
            return () -> {
                System.out.println("[TaskDecorator] 当前线程：" + Thread.currentThread().getName());
                runnable.run();
            };
        }
    }

    @Primary
    @Bean
    public Executor customThreadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10); // 核心线程数
        executor.setMaxPoolSize(20); // 最大线程数
        executor.setQueueCapacity(100); // 队列容量
        executor.setKeepAliveSeconds(60); // 线程空闲时间
        executor.setThreadNamePrefix("custom-exec-"); // 线程名前缀
        executor.setWaitForTasksToCompleteOnShutdown(true); // 关闭时等待任务完成
        executor.setAwaitTerminationSeconds(30); // 关闭等待时间
        executor.setTaskDecorator(new CustomTaskDecorator()); // 注入自定义装饰器
        executor.initialize();
        return executor;
    }
} 